package com.lvt.example.thinking.in.spring.ioc.overview.dependency.lookup;

import com.lvt.example.thinking.in.spring.ioc.overview.annotation.Super;
import com.lvt.example.thinking.in.spring.ioc.overview.domain.User;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.Map;

/**
 * 依赖查找示例：
 * 1、根据名称查找
 * 实时查找
 * 延迟查找
 * 2、根据 Bean 类型查找
 * 单个对象
 * 集合对象
 * 3、根据名称和类型查找
 * 4、根据 Java 注解查找
 * 单个 Bean 对象
 * 集合 Bean 对象
 *
 * @author LT
 * @date 2021/4/18
 */
public class DependencyLookupDemo {

    public static void main(String[] args) {
        BeanFactory beanFactory = new ClassPathXmlApplicationContext("classpath:META-INF/dependency-lookup-context.xml");
        // 根据名称查找
        lookupRealTime(beanFactory);
        lookupLazy(beanFactory);
        // 根据类型查找
        lookupByType(beanFactory);
        lookupCollectionByType(beanFactory);
        // 根据名称和类型查找
        lookupByTypeAndName(beanFactory);
        // 根据 Java 注解查找
        lookupByAnnotation(beanFactory);
    }

    private static void lookupByAnnotation(BeanFactory beanFactory) {
        if (beanFactory instanceof ListableBeanFactory) {
            ListableBeanFactory listableBeanFactory = (ListableBeanFactory) beanFactory;
            Map<String, User> users = (Map) listableBeanFactory.getBeansWithAnnotation(Super.class);
            System.out.println("根据@super注解查找：" + users);
        }
    }

    private static void lookupByTypeAndName(BeanFactory beanFactory) {
        User user = beanFactory.getBean("user", User.class);
        System.out.println("根据名称和类型查找：" + user);
    }

    private static void lookupCollectionByType(BeanFactory beanFactory) {
        if (beanFactory instanceof ListableBeanFactory) {
            ListableBeanFactory listableBeanFactory = (ListableBeanFactory) beanFactory;
            Map<String, User> users = listableBeanFactory.getBeansOfType(User.class);
            System.out.println("查找到的所有的 User 集合对象：" + users);
        }
    }

    private static void lookupByType(BeanFactory beanFactory) {
        User user = beanFactory.getBean(User.class);
        System.out.println("实时查找：" + user);
    }

    private static void lookupLazy(BeanFactory beanFactory) {
        ObjectFactory<User> objectFactory = (ObjectFactory<User>) beanFactory.getBean("objectFactory");
        User userObject = objectFactory.getObject();
        System.out.println("延迟查找：" + userObject);
    }

    private static void lookupRealTime(BeanFactory beanFactory) {
        User user = (User) beanFactory.getBean("user");
        System.out.println("实时查找：" + user);
    }
}
